package br.com.ordersys.web.i18n;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Properties;

public class I18nDictionaryBuilder {
	public static String declare(String bundleName, Locale locale) {
		try {
			InputStream in = getLocaleAwareBundleStream(bundleName,locale);

			if (in != null) {
				Properties p = new Properties();
				p.load(new InputStreamReader(in,"UTF-8")); //por padrão o Properties usa ISO-8859-1, mas nossos arquivos de i18n são gravados em UTF-8 por causa do GWT
				String varId = (String) p.remove("__id");
				
				StringBuilder buf = new StringBuilder();
				buf.append("\nvar i18n_").append(varId).append(" = {\n");
				
				StringBuilder vars = new StringBuilder();
				
				for(Entry<Object,Object> entry : p.entrySet()){
					if(vars.length() > 0){
						vars.append(",\n");
					}
					
					vars.append(entry.getKey()).append(": \"").append(entry.getValue()).append("\"");
				}
				
				buf.append(vars.toString());
				
				buf.append("\n};");
				
				return buf.toString();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	private static InputStream getLocaleAwareBundleStream(String bundleName, Locale locale) throws Exception {
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		
		//primeiro a localização completa (ex: 'en_US'), depois apenas a lingua (ex: 'en'), depois a localização padrão 'pt_BR'
		String[] options = {locale.toString(), locale.getISO3Language(), "pt_BR"};
		InputStream in = null;
		
		for(String s : options){
			String bundle = bundleName + (s.length() > 0 ? "-" : "") + s + ".i18n";
			in = cl.getResourceAsStream(bundle);
			
			if(in != null){
				break;
			}
		}
		
		return in;
	}
}
